package com.an.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 我路由谓词工厂
 *
 * @author: ANHE
 * @createDate: 2024/03/20
 * @version: 1.0.0
 * 需求说明：自定义断言，要求，请求携带userType，并且和yml的配置的相同
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    public static final String USERTYPE = "usertype";

    /**
     * 路由谓词工厂
     *
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    /**
     * 快捷字段顺序
     *
     * @return {@link List }<{@link String }>
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(USERTYPE);
    }



    /**
     * 应用
     * 在这个方法种写具体的规则方法
     *
     * @param config 配置
     * @return {@link Predicate }<{@link ServerWebExchange }>
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {
        return (GatewayPredicate) serverWebExchange -> {
            //获取请求中userType的值
            String userType = serverWebExchange.getRequest().getQueryParams().getFirst(USERTYPE);
            if (userType == null) {
                return false;
            }
            //请求中的值和配置文件中的值进行比较
            return userType.equalsIgnoreCase(config.getUserType());
        };
    }

    /**
     * 配置
     * 这个就是路由断言的规则，重要
     *
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    @Validated
    public static class Config {
        @Setter
        @Getter
        @NotEmpty
        private String userType; //钻、金、银等用户等级
    }
}
